<template>
  <div class="app-container">
    <transition :enter-active-class="animate.searchAnimate.enter" :leave-active-class="animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入模板名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="模板类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择模板类型" clearable>
                <el-option v-for="dict in email_template_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="邮件主题" prop="theme">
              <el-input v-model="queryParams.theme" placeholder="请输入邮件主题" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailTemplate:add']" type="primary" plain icon="Plus" size="mini" @click="handleAdd">新增 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['system:EmailTemplate:edit']"
                type="success"
                plain
                icon="Edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                v-hasPermi="['system:EmailTemplate:remove']"
                type="danger"
                plain
                icon="Delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-hasPermi="['system:EmailTemplate:export']" type="warning" plain icon="Download" size="mini" @click="handleExport"
                >导出
              </el-button>
            </el-col>
            <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
          </el-row>
          <div class="flex items-center w-fit gap-5">
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :page-sizes="[20, 50, 100, 300]"
              :total="total"
              style="height: 30px; margin: 0; padding: 0 !important"
              @pagination="getList"
            />
            <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="EmailTemplateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!--      <el-table-column label="模板ID" align="center" prop="templateId"/>-->
        <el-table-column label="模板类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="email_template_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="模板名称" align="center" prop="name" />
        <el-table-column label="邮件主题" align="center" prop="theme" />
        <!--      <el-table-column label="邮件模板" align="center" prop="template" />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-hasPermi="['system:EmailTemplate:edit']" size="mini" type="text" icon="Edit" @click="handleUpdate(scope.row)"
              >修改
            </el-button>
            <el-button v-hasPermi="['system:EmailTemplate:remove']" size="mini" type="text" icon="Delete" @click="handleDelete(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-5 mr-[-0.5rem]">
        <div class="flex justify-end items-center w-fit gap-5">
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :page-sizes="[20, 50, 100, 300]"
            :total="total"
            style="height: 30px; margin: 0; padding: 0 !important"
            @pagination="getList"
          />
          <right-toolbar v-model:showSearch="showSearch" :show-search-btn="false" @query-table="getList"></right-toolbar>
        </div>
      </div>
    </el-card>

    <!-- 添加或修改邮件模板对话框 -->
    <el-dialog v-model="open" :title="title" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择模板类型">
            <el-option v-for="dict in email_template_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮件主题" prop="theme">
          <el-input v-model="form.theme" placeholder="请输入邮件主题" />
        </el-form-item>
        <el-form-item label="邮件模板" prop="template">
          <vue-ueditor-wrap v-model="form.template" :config="ueditorConfig"></vue-ueditor-wrap>
          <div>
            <span v-for="dict in order_email_field" style="margin-right: 15px"
              >{{ dict.label }}
              <span style="color: #b94a48" @click="copyToClipboard('{' + dict.value + '}')">{{ '{' + dict.value + '}' }}</span>
            </span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listEmailTemplate, getEmailTemplate, delEmailTemplate, addEmailTemplate, updateEmailTemplate } from '@/api/email/EmailTemplate';

export default {
  name: 'EmailTemplate',
  data() {
    return {
      email_template_type: [],
      order_email_field: [],
      showSearch: false,
      ueditorConfig: {
        UEDITOR_HOME_URL: '/ueditor/',
        toolbars: [
          [
            'source', //源代码
            'undo', //撤销
            'redo', //重做
            'bold', //加粗
            'indent', //首行缩进
            'snapscreen', //截图
            'italic', //斜体
            'underline', //下划线
            'print', //打印
            'horizontal', //分隔线
            'inserttable', //插入表格
            'edittable', //表格属性
            'insertrow', //前插入行
            'insertcol', //前插入列
            'mergeright', //右合并单元格
            'mergedown', //下合并单元格
            'deleterow', //删除行
            'deletecol', //删除列
            'splittorows', //拆分成行
            'splittocols', //拆分成列
            'splittocells', //完全拆分单元格
            'deletecaption', //删除表格标题
            'inserttitle', //插入标题
            'mergecells', //合并多个单元格
            'edittd', //单元格属性
            'deletetable', //删除表格
            // 'fontfamily', //字体
            // 'fontsize', //字号
            // 'paragraph', //段落格式
            'simpleupload', //单图上传
            'insertimage', //多图上传
            'attachment', //附件
            'link', //超链接
            'emotion', //表情
            'spechars', //特殊字符
            'searchreplace', //查询替换
            'map', //Baidu地图
            'justifyleft', //居左对齐
            'justifyright', //居右对齐
            'justifycenter', //居中对齐
            'justifyjustify', //两端对齐
            'forecolor', //字体颜色
            'backcolor', //背景色
            'insertorderedlist', //有序列表
            'insertunorderedlist', //无序列表
            'rowspacingtop', //段前距
            'rowspacingbottom', //段后距
            'lineheight', //行间距
            'autotypeset', //自动排版
            'template', //模板
            'scrawl' //涂鸦
          ]
        ],
        autoHeightEnabled: true,
        initialFrameHeight: 300
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 邮件模板表格数据
      EmailTemplateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: null,
        type: null,
        theme: null,
        isDelete: null,
        createId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '模板类型不能为空', trigger: 'blur' }],
        theme: [{ required: true, message: '邮件主题不能为空', trigger: 'blur' }],
        template: [{ required: true, message: '邮件模板不能为空', trigger: 'blur' }]
      }
    };
  },
  watch: {
    open(val) {
      if (!val) {
        this.reset();
      }
    }
  },
  async created() {
    let res = await this.useDict('email_template_type', 'order_email_field');
    await this.getList();
    setTimeout(() => {
      this.order_email_field = res.order_email_field;
      this.email_template_type = res.email_template_type;
    }, 1000);
  },
  methods: {
    /** 查询邮件模板列表 */
    getList() {
      this.loading = true;
      listEmailTemplate(this.queryParams).then((response) => {
        this.EmailTemplateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        name: null,
        type: null,
        theme: null,
        template: '',
        isDelete: null,
        createId: null,
        createName: null,
        createTime: null,
        updateId: null,
        updateName: null,
        updateTime: null
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.assign(this.queryParams, {
        name: null,
        type: null,
        theme: null,
        isDelete: null,
        createId: null
      });
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.templateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加邮件模板';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids;
      getEmailTemplate(templateId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = '修改邮件模板';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.saveOrUpdate();
        }
      });
    },
    saveOrUpdate() {
      this.form.template = encodeURIComponent(this.form.template.toString());
      if (this.form.templateId != null) {
        updateEmailTemplate(this.form).then((response) => {
          this.$modal.msgSuccess('修改成功');
          this.open = false;
          this.getList();
        });
      } else {
        addEmailTemplate(this.form).then((response) => {
          this.$modal.msgSuccess('新增成功');
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal
        .confirm('是否确认删除邮件模板编号为"' + templateIds + '"的数据项？')
        .then(function () {
          return delEmailTemplate(templateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/EmailTemplate/export',
        {
          ...this.queryParams
        },
        `EmailTemplate_${new Date().getTime()}.xlsx`
      );
    },
    copyToClipboard(text) {
      const el = document.createElement('textarea');
      el.value = text;
      el.setAttribute('readonly', '');
      el.style.position = 'absolute';
      el.style.left = '-9999px';
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      // 可以添加一些提示或者其他操作
      this.$modal.msgSuccess('已复制到剪切板');
    }
  }
};
</script>
